import { getUserInfo } from "@/api/user";
import { User } from "@/typings";

export default {
  namespaced: true,
  state: {
    userInfo: { nickName: "匿名用户" } as User,
    invitorId: 0,
    roles: [] as string[],
    isAdmin: false,
  },
  mutations: {
    setUserInfo(state: any, value: User) {
      state.userInfo = value;
      if (value.roles) {
        state.roles = value.roles.map((role) => role.roleKey);
        if (state.roles.includes("admin")) {
          state.isAdmin = true;
        }
      }
    },
    setInvitorId(state: any, value: any) {
      state.invitorId = value;
    },
  },
  actions: {
    async getUserInfo({ state, commit }) {
      if (state.userInfo.userId) {
        return state.userInfo;
      } else {
        let user = await getUserInfo();
        commit("setUserInfo", user);
      }
    },
  },
};
